<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="30%"
    destroy-on-close
  >
    <el-form
      ref="form"
      v-loading="loading"
      :model="formInfo"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item prop="oldPassword" label-width="0px">
        <el-input
          v-model="formInfo.oldPassword"
          type="password"
          placeholder="旧密码"
          tabindex="1"
        ><i slot="prefix" class="el-input__icon el-icon-lock" /></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" label-width="0px">
        <el-input
          v-model="formInfo.newPassword"
          type="password"
          placeholder="新密码"
          tabindex="2"
        ><i slot="prefix" class="el-input__icon el-icon-lock" /></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">修改密码</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { modifyPassword } from '@/api/user'

export default {
  name: 'ModifyPassword',
  components: {},
  filters: {},
  data() {
    var password = (rule, value, callback) => {
      const regexp = new RegExp('^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,20}$')
      if (!regexp.test(value)) {
        callback(new Error('密码需符合：大小写字母、数字、特殊字符且至少8位'))
      } else {
        callback()
      }
    }
    return {
      title: '修改密码',
      visible: false,
      formInfo: {
        id: this.$store.getters.id,
        oldPassword: '',
        newPassword: ''
      },
      loading: false,
      rules: {
        // oldPassword: [
        //   { validator: password, trigger: 'blur' }
        // ],
        newPassword: [
          { validator: password, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    onSubmit() {
      console.log(this.$route.params)
      modifyPassword(this.formInfo)
        .then(res => {
          this.$message.success(res.result)
          setTimeout(_ => this.logout(), 1000)
        }).catch(err => {
          console.log(err)
        })
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login`)
    }
  }
}
</script>
